package com.gupao.dubbo.netty.server;

import com.gupao.dubbo.netty.server.register.IRegister;
import com.gupao.dubbo.netty.server.register.RegisterImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.util.HashMap;
import java.util.Map;

public class RpcServer {

    private static final String serviceAddress = "127.0.0.1:9090";

    private static IRegister registryCenter = new RegisterImpl();

    private static Map<String, Object> handlerMap = new HashMap();

    public static void handle(String serviceName, Object instance) {
        handlerMap.put(serviceName, instance);
    }

    public static void publish() {
        for (String serviceName : handlerMap.keySet()) {
            registryCenter.register(serviceName, serviceAddress);
        }

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap().group(boss, worker).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pip = ch.pipeline();
                    pip.addLast("frameDecodeer", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));;
                    pip.addLast("frameEncode", new LengthFieldPrepender(4));
                    pip.addLast("encode", new ObjectEncoder());
                    pip.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(Thread.currentThread().getContextClassLoader())));
                    pip.addLast(new RpcHandler(handlerMap));

                }
            });
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

            Channel channel = serverBootstrap.bind(9090).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
